package spring.webflux.handler;

import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import spring.webflux.entity.Personnel;
import spring.webflux.service.PersonnelService;

@RequiredArgsConstructor
public class PersonnelHandler {

    private final PersonnelService personnelService;

    public Mono<ServerResponse> getPersonnelById(ServerRequest request) {
        int id = Integer.valueOf(request.pathVariable("id"));
        // 空值处理
        Mono<ServerResponse> noFound = ServerResponse.notFound().build();
        Mono<Personnel> personnelMono = personnelService.getPersonnelById(id);
        return personnelMono.flatMap(p -> ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(personnelMono, Object.class))
                .switchIfEmpty(noFound);
    }

    public Mono<ServerResponse> getAllPersonnel(ServerRequest request) {
        Flux<Personnel> allPersonnel = personnelService.getAllPersonnel();
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(allPersonnel, Personnel.class);
    }

    public Mono<ServerResponse> insertPersonnel(ServerRequest request) {
        Mono<Personnel> personnelMono = request.bodyToMono(Personnel.class);
        return ServerResponse.ok().build(personnelService.insertPersonnel(personnelMono));
    }
}
